package com.allen.admin.config.shiro;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.springframework.cache.support.SimpleValueWrapper;

import java.util.Collection;
import java.util.Set;

/**
 * 
 * @author xiaoqing.chen
 *
 */
public class ShiroCacheManager implements CacheManager {
	
	private org.springframework.cache.CacheManager cacheManager;
	
	public org.springframework.cache.CacheManager getCacheManager() {
		return cacheManager;
	}

	public void setCacheManger(org.springframework.cache.CacheManager cacheManager) {
		this.cacheManager = cacheManager;
	}

	@Override
	public <K, V> Cache<K, V> getCache(String name) throws CacheException {
		org.springframework.cache.Cache cache = getCacheManager().getCache(name);
        return new CacheWrapper<K, V>(cache);
	}
	
	private class CacheWrapper<K, V> implements Cache<K, V> {

		private org.springframework.cache.Cache cache;

		public CacheWrapper(org.springframework.cache.Cache cache) {
			this.cache = cache;
		}

		@SuppressWarnings("unchecked")
		@Override
		public V get(K key) throws CacheException {
			Object value = cache.get(key);
			if (value instanceof SimpleValueWrapper) {
				return (V) ((SimpleValueWrapper) value).get();
			}
			return (V) value;
		}

		@Override
		public V put(K key, V value) throws CacheException {
			cache.put(key, value);
			return value;
		}

		@SuppressWarnings("unchecked")
		@Override
		public V remove(K key) throws CacheException {
			Object value = get(key);
			cache.evict(key);
			return (V) value;
		}

		@Override
		public void clear() throws CacheException {
			cache.clear();
		}

		@Override
		public int size() {
			throw new UnsupportedOperationException("invoke spring cache abstract size method not supported");
		}

		@Override
		public Set<K> keys() {
			throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported");
		}

		@Override
		public Collection<V> values() {
			throw new UnsupportedOperationException("invoke spring cache abstract values method not supported");
		}

	}
	
}
